//
//  MessageManager.m
//  onlineCustoSDK
//
//  Created by 曹宗华 on 2017/12/19.
//  Copyright © 2017年 com.netinfosz. All rights reserved.
//

#import "MessageManager.h"
static MessageManager *instance=nil;
@implementation MessageManager
+(instancetype)shareInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance=[[self alloc] init];
    });
    return instance;
}
- (NSManagedObjectModel*)model
{
    if (_model!=nil) {
        return _model;
    }
//    NSBundle *bundle=[NSBundle bundleWithIdentifier:onlineCustoSDK_IOS_FRAMEWORK_BUNDLE_ID];
//    ICLog(@"ChatModel url bundle:%@", bundle);
//
//    NSBundle *testBundle = [NSBundle bundleWithIdentifier:@"YB007PodTest.framework"];
//    ICLog(@"testBundle:%@", testBundle);
//
//    NSURL *modelURL=[bundle URLForResource:@"ChatModel" withExtension:@"mom"];
    //SDKResouces 资源自动打包到 res_bundle.bundle中
    NSString* bundlePath = [NSBundle.mainBundle pathForResource:@"res_bundle" ofType:@"bundle"];
    NSBundle* resBundle = [NSBundle bundleWithPath:bundlePath];
    
    NSURL* modelURL = [resBundle URLForResource:@"ChatModel" withExtension:@"mom"];
    
    
    ICLog(@"ChatModel url:%@", modelURL);
    _model=[[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _model;
}
- (NSPersistentStoreCoordinator*)store
{
    if(!_store)
    {
        _store=[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.model];
//        NSString *docs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *sqlPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject
                             stringByAppendingPathComponent:@"message.sqlite"];
        NSURL *url = [NSURL fileURLWithPath:sqlPath];
        NSError *error = nil;
        NSPersistentStore *store2= [_store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error];
        if (store2 == nil) { // 直接抛异常
//            [NSException raise:@"添加数据库错误" format:@"%@", [error localizedDescription]];
              NSLog(@"addError = %@", error);
    }
    }
    return _store;
}
- (NSManagedObjectContext*)context
{
    if(_context!=nil)
    {
        return _context;
        
    }
    _context=[[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    _context.persistentStoreCoordinator=self.store;
    return _context;
}
- (void)createMessageObject:(ICMessageFrame*)messageFrame
{
   NSManagedObject  *messageObject = [NSEntityDescription insertNewObjectForEntityForName:@"Message" inManagedObjectContext:self.context];
//    messageObject.content=messageFrame.model.message.content;
//    messageObject.from=messageFrame.model.message.from;
//    messageObject.to=messageFrame.model.message.to;
//    messageObject.type=messageFrame.model.message.type;
//    messageObject.path=messageFrame.model.mediaPath;
//    messageObject.isSender=messageFrame.model.isSender;
   
    [messageObject setValue:messageFrame.model.mediaPath forKey:@"path"];
    [messageObject setValue:messageFrame.model.message.from forKey:@"from"];
    [messageObject setValue:messageFrame.model.message.to forKey:@"to"];
    [messageObject setValue:messageFrame.model.message.type forKey:@"type"];
    [messageObject setValue:messageFrame.model.message.content forKey:@"content"];
    [messageObject setValue:@(messageFrame.model.isSender) forKey:@"isSender"];
    [messageObject setValue:@(messageFrame.model.message.deliveryState) forKey:@"deliveryState"];
//    messageFrame.model.message.date
    NSDate *messageDate=[ICMessageHelper timeFormatWithDate3:messageFrame.model.message.date];
//    messageObject.date=messageDate;
    [messageObject setValue:messageDate forKey:@"date"];
    NSError *error = nil;
    
    // 同步到数据库并判断
    if ([self.context save:&error]) {
//         NSLog(@"插入创建了一个存储的消息对象");
//        [self.myDataArray addObject:std];
//        [self.myTableView reloadData];
    } else {
        NSLog(@"insert error = %@", error);
    }
}
- (NSArray*)queryFromDB
{
    NSArray *objectAry=nil;
    NSFetchRequest *request=[[NSFetchRequest alloc] init];
    NSEntityDescription *desc=[NSEntityDescription entityForName:ENTITY_Message inManagedObjectContext:self.context];
    [request setEntity:desc];
    NSSortDescriptor  *sort=[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES];
    request.sortDescriptors=[NSArray arrayWithObject:sort];
//    [request setFetchLimit:10];
//    [request setFetchOffset:10];
    NSError *error = nil;
    
    objectAry=[self.context  executeFetchRequest:request error:&error];
    if (error) {
        [NSException raise:@"查询错误" format:@"%@", [error localizedDescription]];
    }
//    int i=0;
//    for (NSManagedObject *obj in objectAry)
//    {
//        NSLog(@"content=%@%d", [obj valueForKey:@"content"],++i);
//    }
    
    return objectAry;
}
- (void)deleteData
{
    NSFetchRequest *request=[[NSFetchRequest alloc] init];
    NSEntityDescription *desc=[NSEntityDescription entityForName:ENTITY_Message inManagedObjectContext:self.context];
    [request setEntity:desc];
    NSError *error = nil;
    NSArray *resultAry=[self.context executeFetchRequest:request error:&error];
    NSLog(@"查询结果：%@",resultAry);
    if(resultAry.count>0)
    {
        int i=0;
        for (NSManagedObject *obj in resultAry)
        {
            NSLog(@"删除:content=%@%d", [obj valueForKey:@"content"],++i);
//            NSLog(@"删除+%d",i);
            [self.context deleteObject:obj];
        }
        [self.context save:&error];
    }else
    {
         NSLog(@"没有符合条件的结果");
    }
}
@end
